package com.filters;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.common.models.RetCode;
import com.common.models.RetResult;
import com.common.util.redis.RedisUtils;
import com.google.gson.Gson;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;

@Component
public class CustomerTokenFilter extends ZuulFilter{

    private static Logger log = LoggerFactory.getLogger(CustomerTokenFilter.class);
    
	@Autowired
	private RedisUtils redisUtils;
	
    //需要进行token验证的url
    private static List<String> filterUrlList = new ArrayList<String>(Arrays.asList(
    		"forMy"
    	)
    );
    
    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {

        //检查用户请求的url是否需要token校验
        String requestUrl = RequestContext.getCurrentContext().getRequest().getRequestURL().toString();
        for(String url : filterUrlList )
        {
        	if(requestUrl.indexOf(url) > -1)
        	{
        		return true;
        	}
        }
        
        return false;
    }

    @Override
    public Object run() {
    	
    	RetResult ret = new RetResult();
    	ret.setCode(RetCode.SUCCESS);
    	
        RequestContext ctx = RequestContext.getCurrentContext();
        HttpServletRequest request = ctx.getRequest();
        log.info(String.format("%s >>> %s", request.getMethod(), request.getRequestURL().toString()));
        String token = request.getParameter("token");
        
        if(token == null || token.equals("")) {
        	ret.setCode(RetCode.PARAM_ERR);
        	ret.setMsg(RetCode.PARAM_ERR_MSG);
        }
        
        //从redis缓存中根据token获取顾客个人信息。如果有，则token验证成功，否则失败
        Object customer = redisUtils.get("token" + token);
        if( null == customer )
        {
        	ret.setCode(RetCode.TOKEN_ERROR);
        	ret.setMsg(RetCode.TOKEN_ERROR_MSG);
        }
        
        if(ret.getCode() != RetCode.SUCCESS)
        {
        	Gson gson = new Gson();
        	String jsonStr = gson.toJson(ret);
            ctx.setSendZuulResponse(false);
            ctx.setResponseStatusCode(200);
            
            try {
                ctx.getResponse().getWriter().write(jsonStr);
            }catch (Exception e){
            	e.printStackTrace();
            }

            return null;
        }
        
        log.info("ok");
        return null;
    }
}